﻿using System;
using Greg.WPF.Utility;
using NLog;

namespace SessionHunter.Utilities
{
    /// <summary>
    /// General helper class, for application wide functionality
    /// </summary>
    public static class Helper
    {
        private static bool _isUnitTest = false;

        /// <summary>
        /// Gets or sets a value indicating whether this instance is runing within a unit test.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is unit test; otherwise, <c>false</c>.
        /// </value>
        public static bool IsUnitTest
        {
            get { return _isUnitTest; }
            set { _isUnitTest = value; }
        }

        /// <summary>
        /// Handles an exception by displaying the details in a friendly dialog
        /// </summary>
        /// <param name="logger">The class specific logger to use.</param>
        /// <param name="message">The message.</param>
        /// <param name="ex">The ex.</param>
        public static void HandleException(Logger logger, string message, Exception ex)
        {
            // Log the exception
            logger.ErrorException(message, ex);

            if (!IsUnitTest)
            {
                // Show a dialog with details about the exception
                ExceptionMessageBox window = new ExceptionMessageBox(ex, message);
                window.ShowDialog();
            }
            else
                throw new Exception(message, ex);
        }

        /// <summary>
        /// Takes the hex string and converts it to an array.  Useful for converting the session data to the
        /// byte array we need for the SessionStateItem
        /// </summary>
        /// <param name="hex">The hex.</param>
        /// <returns></returns>
        public static byte[] StringToByteArray(String hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                if (i < hex.Length - 2) // For contract
                    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }
            return bytes;
        }
    }
}
